package com.david.fastmsg.service.impl;

import cn.hutool.core.codec.Base32;
import cn.hutool.core.net.NetUtil;
import com.david.fastmsg.Constant.Constant;
import com.david.fastmsg.Constant.Param;
import com.david.fastmsg.enums.FileType;
import com.david.fastmsg.enums.ResponseEnum;
import com.david.fastmsg.exception.RespException;
import com.david.fastmsg.service.FileService;
import com.david.fastmsg.utils.Config;
import com.david.fastmsg.utils.NettyConfig;
import com.david.fastmsg.utils.ResponseUtils;
import com.david.fastmsg.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author qzw
 * @date 2021/9/13
 */
@Service
public class FileServiceImpl implements FileService {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileServiceImpl.class);


    @Autowired
    private Config config;


    /**
     * 上传文件
     * @param file
     * @return
     */
    @Override
    public Map<String, Object> upload(MultipartFile file) {
        // 获取文件名称
        String fileName = file.getOriginalFilename();
        String name = StringUtils.split(fileName,".")[0];
        // 获取文件的后缀名
        String fileType = null;
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        LOGGER.info("上传文件，[fileName]:" + fileName + ",[suffixName]: " + suffixName);
        String filePath = config.getBasePath();
        boolean isMatch = Pattern.matches(Constant.imgPattern, suffixName);
        if (isMatch) {
            filePath += config.getPicturePath() + Utils.genFilePath();
            fileType = FileType.PIC.getType();
//        } else if(suffixName.equals(".mp4")) {
//            filePath += config.getVideoPath() + Utils.genFilePath();
        } else {
            filePath += config.getFilePath() + Utils.genFilePath();
            fileType = FileType.FILE.getType();
        }

        File destDir = new File(filePath);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(new File(destDir, fileName));
            outputStream.write(file.getBytes());
            outputStream.close();
            String previewPath = null;
            String downloadPath = null;
            if (fileType.equals(FileType.PIC.getType())) {
                previewPath = Constant.HTTP + NetUtil.getLocalhost().getHostAddress() + ":" + config.getServerPort() + "/file/preview/" + Base32.encode(destDir + "/" + name) + suffixName;
            } else {
                downloadPath = Constant.HTTP + NetUtil.getLocalhost().getHostAddress() + ":" + config.getServerPort() + "/file/download/" + Base32.encode(destDir + "/" + name) + suffixName;
            }
            Map<String, Object> returnMap = ResponseUtils.success();
            returnMap.put(Param.PREVIEW_PATH, previewPath);
            returnMap.put(Param.DOWNLOAD_PATH, downloadPath);
            returnMap.put(Param.FILE_TYPE, fileType);
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RespException(ResponseEnum.ERR_SVC_UPLOAD_FILE_EXCEPTION);
        }

    }

    @Override
    public File preview(String fileName) {
        String[] split = StringUtils.split(fileName,".");
        String destPath = Base32.decodeStr(split[0]) + "." +split[1];
        return new File(destPath);
    }
}
